#!/bin/bash

# Tiny QA - 推送到阿里云容器镜像服务
# 支持自动登录和镜像推送

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
LOCAL_IMAGE="tiny-qa:latest"
REGISTRY="registry.cn-hangzhou.aliyuncs.com"  # 阿里云杭州镜像仓库
NAMESPACE="your-namespace"  # 需要替换为你的命名空间
REPO_NAME="tiny-qa"
TAG="latest"

# 完整的远程镜像名称
REMOTE_IMAGE="${REGISTRY}/${NAMESPACE}/${REPO_NAME}:${TAG}"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Tiny QA - 推送到阿里云容器镜像服务${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${YELLOW}🔧 推送配置:${NC}"
echo -e "  本地镜像: ${LOCAL_IMAGE}"
echo -e "  远程镜像: ${REMOTE_IMAGE}"
echo -e "  镜像仓库: ${REGISTRY}"
echo -e "  命名空间: ${NAMESPACE}"
echo ""

# 检查本地镜像是否存在
if ! docker images | grep -q "tiny-qa.*latest"; then
    echo -e "${RED}❌ 本地镜像 ${LOCAL_IMAGE} 不存在${NC}"
    echo -e "${YELLOW}💡 请先构建镜像:${NC}"
    echo -e "  ./scripts/docker-build-stable.sh"
    exit 1
fi

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}❌ Docker未运行，请先启动Docker Desktop${NC}"
    exit 1
fi

# 配置命名空间
echo -e "${YELLOW}📝 配置命名空间...${NC}"
echo -e "${BLUE}当前命名空间: ${NAMESPACE}${NC}"
read -p "是否修改命名空间？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    read -p "请输入新的命名空间: " NEW_NAMESPACE
    if [[ -n "$NEW_NAMESPACE" ]]; then
        NAMESPACE="$NEW_NAMESPACE"
        REMOTE_IMAGE="${REGISTRY}/${NAMESPACE}/${REPO_NAME}:${TAG}"
        echo -e "${GREEN}✅ 命名空间已更新为: ${NAMESPACE}${NC}"
    fi
fi

# 配置标签
echo -e "${YELLOW}📝 配置镜像标签...${NC}"
echo -e "${BLUE}当前标签: ${TAG}${NC}"
read -p "是否修改标签？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    read -p "请输入新的标签: " NEW_TAG
    if [[ -n "$NEW_TAG" ]]; then
        TAG="$NEW_TAG"
        REMOTE_IMAGE="${REGISTRY}/${NAMESPACE}/${REPO_NAME}:${TAG}"
        echo -e "${GREEN}✅ 标签已更新为: ${TAG}${NC}"
    fi
fi

echo ""
echo -e "${YELLOW}🚀 开始推送镜像...${NC}"
echo -e "${BLUE}目标镜像: ${REMOTE_IMAGE}${NC}"
echo ""

# 给镜像打标签
echo -e "${YELLOW}📦 给镜像打标签...${NC}"
docker tag "${LOCAL_IMAGE}" "${REMOTE_IMAGE}"
echo -e "${GREEN}✅ 镜像标签完成${NC}"

# 登录阿里云容器镜像服务
echo -e "${YELLOW}🔐 登录阿里云容器镜像服务...${NC}"
echo -e "${BLUE}请在弹出的浏览器窗口中完成登录${NC}"
docker login "${REGISTRY}"

# 推送镜像
echo -e "${YELLOW}📤 推送镜像到阿里云...${NC}"
docker push "${REMOTE_IMAGE}"

echo ""
echo -e "${GREEN}🎉 镜像推送成功！${NC}"
echo -e "${BLUE}📋 镜像信息:${NC}"
echo -e "  镜像地址: ${REMOTE_IMAGE}"
echo -e "  仓库地址: https://cr.console.aliyun.com/cn-hangzhou/instances/repositories"
echo ""

# 显示拉取命令
echo -e "${BLUE}📥 拉取命令:${NC}"
echo -e "  docker pull ${REMOTE_IMAGE}"
echo ""

# 显示运行命令
echo -e "${BLUE}🚀 运行命令:${NC}"
echo -e "  docker run -d -p 5002:5002 --name tiny-qa ${REMOTE_IMAGE}"
echo ""

# 清理本地标签
read -p "是否删除本地标签？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}🧹 清理本地标签...${NC}"
    docker rmi "${REMOTE_IMAGE}"
    echo -e "${GREEN}✅ 本地标签已清理${NC}"
fi

echo -e "${GREEN}✅ 推送流程完成！${NC}" 